﻿#include "GLLInc.h"
#include "GLLLevelManager.h"
#include "GLLLevel.h"
#include "GLLResMgr.h"
#include "GLLTheSystem.h"


namespace GLL
{
	Level* LevelManager::_new_Level( Level::ID id)
	{
		return GLL_NEW Level(this, id);
	}

	void LevelManager::_delete_Level(Level* p)
	{
		GLL_DEL(p);
	}

	LvlSrdPtr LevelManager::Create( Level::ID id )
	{
		Level* pLv = _new_Level(id);
		if(!pLv)
		{
			StringStream strm;
			strm << "Create level failed. id: "<< id;
			GLL_Throw(strm);
		}
		pLv->Init();

		LvlSrdPtr srdPtr(pLv);

		if(!_currentLevel){
			_currentLevel = srdPtr;
		}

		_levels[id] = srdPtr;
		return srdPtr;
	}

	void LevelManager::DestroyThread()
	{

	}

	void LevelManager::DestroyAll()
	{
		if(_currentLevel)
		{
			_currentLevel.reset();
		}

		LevelMap::iterator iter = _levels.begin();
		for(; iter != _levels.end(); ++iter) 
		{
			LvlSrdPtr ptr = iter->second;
			ptr->Final();
			ptr.reset();
		}

		_levels.clear();
	}

	void LevelManager::Destroy( Level::ID id )
	{
		LvlSrdPtr ptr = _Pop(id);
		ptr->Final();
		ptr.reset();
	}

	LvlSrdPtr LevelManager::Get( Level::ID sid )
	{
		if(_currentLevel->_id == sid) return _currentLevel;

		LevelMap::iterator iter = _levels.find(sid);
		if(iter == _levels.end()) 
		{
			StringStream strm;
			strm << "Level does not exist : " << sid;
			GLL_Throw(strm);
		}
		return iter->second;
	}

	LvlSrdPtr LevelManager::_Pop( Level::ID sid )
	{
		if(!_currentLevel) return LvlSrdPtr();
		if(_currentLevel->_id == sid)
		{
			_currentLevel.reset();
		}

		LevelMap::iterator iter = _levels.find(sid);
		if(iter == _levels.end()) 
		{
			return LvlSrdPtr();
		}
		LvlSrdPtr ret = iter->second;
		_levels.erase(iter);
		return ret;
	}

	void LevelManager::Update(TimeMS ms)
	{
		_currentLevel->Update(ms);
	}

	LevelManager::LevelManager()
	{
		_destroyThread = nullptr;
	}
}//GLL